/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import BUSServices.QLNSBUSWebService;
import BUSServices.QLNSBUSWebService_Service;
import BUSServices.Sach;
import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;

/**
 *
 * @author USER
 */
public class GioHang extends ActionSupport implements ServletRequestAware, SessionAware{

    
   private HttpServletRequest request;
   private Map session;
   
    QLNSBUSWebService_Service service;
    QLNSBUSWebService port;
   
   private List<Sach> gioHang = new ArrayList<Sach>();
   private float thanhTien;
   private float tongTien;
   
   public GioHang(){
        service = new QLNSBUSWebService_Service();
        port = service.getQLNSBUSWebServicePort();
   }
   
    public String execute(){
        if(session.get("gioHang")== null){
            session.put("gioHang", gioHang);
        }
        else{
            gioHang = (List<Sach> )session.get("gioHang");
        }
       
        String action = request.getParameter("action");
        if(action != null & action.equals("Them")){
            int maSach = Integer.parseInt(request.getParameter("maSach"));
            //kiểm tra mã sách này đã có trong giỏ hàng hay chưa.
            boolean kq = false;
            for(int i = 0; i < gioHang.size(); i++){
                Sach s = gioHang.get(i);
                if(s.getMaSach() == maSach){
                    s.setSoLuongBan(s.getSoLuongBan() + 1);
                    
                    kq = true;
                    break;
                }
                
                thanhTien = s.getSoLuongBan() * s.getGiaBan();
            }
            if(kq==false){
                Sach s = port.laySachTheoMaSach(maSach);
                s.setSoLuongBan(1);
                thanhTien = s.getSoLuongBan() * s.getGiaBan();
                gioHang.add(s);
            }
            
        }
        
        tongTien = 0;
        for(int i = 0; i < gioHang.size(); i++){
            tongTien = tongTien + gioHang.get(i).getGiaBan() * gioHang.get(i).getSoLuongBan();
        }
       
        
        return SUCCESS;
    }
    public List<Sach> getGioHang() {
        return gioHang;
    }

    public float getThanhTien() {
        return thanhTien;
    }

    public float getTongTien() {
        return tongTien;
    }

    
    @Override
    public void setServletRequest(HttpServletRequest hsr) {
        this.request = hsr;
    }

    @Override
    public void setSession(Map<String, Object> map) {
       this.session = map;
    }
    
}
